using System;
using System.Collections.Generic;
using muduoDotNet;
using muduoDotNet.Messages;
using Google.Protobuf;

namespace muduoDotNet.Examples.ReflectionProtocol
{
    /// <summary>
    /// 自定义业务处理器
    /// 继承自BaseMessageHandler，利用反射自动注册和处理消息
    /// </summary>
    public class CustomBusinessHandler : BaseMessageHandler
    {
        private int _echoRequestCount = 0;
        private int _heartbeatCount = 0;
        private int _statusMessageCount = 0;
        private int _unhandledMessageCount = 0;

        /// <summary>
        /// 处理Echo请求消息
        /// 方法名遵循Handle+消息类型名的约定，会被基类自动注册
        /// </summary>
        private void HandleEchoRequest(TcpConnection connection, EchoRequest request)
        {
            _echoRequestCount++;
            Logger.Info($"Received EchoRequest #{_echoRequestCount} from {connection.Name}: '{request.Message}' (client: {request.ClientId})");
            
            // 创建Echo响应
            var response = new EchoResponse
            {
                Message = $"Custom Echo: {request.Message}",
                Timestamp = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds(),
                ServerId = "ReflectionProtocolServer",
                StatusCode = 200
            };
            
            // 发送响应
            connection.SendProtobufMessage(response);
            Logger.Debug($"Sent EchoResponse to {connection.Name}: '{response.Message}'");
        }

        /// <summary>
        /// 处理心跳消息
        /// 方法名遵循Handle+消息类型名的约定，会被基类自动注册
        /// </summary>
        private void HandleHeartbeat(TcpConnection connection, Heartbeat heartbeat)
        {
            _heartbeatCount++;
            Logger.Debug($"Received Heartbeat #{_heartbeatCount} from {connection.Name} (node: {heartbeat.NodeId})");
            
            // 回复心跳
            var heartbeatResponse = new Heartbeat
            {
                Timestamp = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds(),
                NodeId = "ReflectionProtocolServer"
            };
            
            connection.SendProtobufMessage(heartbeatResponse);
        }

        /// <summary>
        /// 处理状态消息
        /// 方法名遵循Handle+消息类型名的约定，会被基类自动注册
        /// </summary>
        private void HandleStatusMessage(TcpConnection connection, StatusMessage status)
        {
            _statusMessageCount++;
            var typeStr = status.Type.ToString();
            Logger.Info($"Received StatusMessage #{_statusMessageCount} from {connection.Name}: [{typeStr}] {status.Message}");
            
            if (status.Metadata.Count > 0)
            {
                foreach (var kv in status.Metadata)
                {
                    Logger.Debug($"  Metadata: {kv.Key} = {kv.Value}");
                }
            }
        }

        /// <summary>
        /// 处理通用消息
        /// 方法名遵循Handle+消息类型名的约定，会被基类自动注册
        /// </summary>
        private void HandleDataPacket(TcpConnection connection, IMessage message)
        {
            Logger.Info($"Received message from {connection.Name}: type = {message.GetType().Name}");
            
            // 简单回显收到的消息类型
            var response = new StatusMessage
            {
                Type = StatusMessage.Types.StatusType.Info,
                Message = $"Received message of type {message.GetType().Name}",
                Timestamp = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds()
            };
            response.Metadata.Add("message_type", message.GetType().Name);
            
            connection.SendProtobufMessage(response);
        }

        /// <summary>
        /// 处理连接信息
        /// 方法名遵循Handle+消息类型名的约定，会被基类自动注册
        /// </summary>
        private void HandleConnectionInfo(TcpConnection connection, ConnectionInfo connectionInfo)
        {
            Logger.Info($"Received ConnectionInfo from {connection.Name}: client_id = {connectionInfo.ConnectionId}");
            
            // 发送连接确认
            var statusMessage = new StatusMessage
            {
                Type = StatusMessage.Types.StatusType.Info,
                Message = "Connection information received",
                Timestamp = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds()
            };
            statusMessage.Metadata.Add("server_time", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));
            
            connection.SendProtobufMessage(statusMessage);
        }

        /// <summary>
        /// 处理断开连接请求
        /// 方法名遵循Handle+消息类型名的约定，会被基类自动注册
        /// </summary>
        private void HandleDisconnectRequest(TcpConnection connection, DisconnectRequest disconnectRequest)
        {
            Logger.Info($"Received DisconnectRequest from {connection.Name}: reason = {disconnectRequest.Reason}");
            
            // 发送确认消息后断开连接
            var statusMessage = new StatusMessage
            {
                Type = StatusMessage.Types.StatusType.Info,
                Message = "Disconnection request acknowledged",
                Timestamp = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds()
            };
            
            connection.SendProtobufMessage(statusMessage);
            
            // 断开连接，确保确认消息发送出去
            connection.Loop.QueueInLoop(() =>
            {
                connection.Shutdown();
            });
        }

        /// <summary>
        /// 重写处理未识别消息的方法
        /// 增加未识别消息计数
        /// </summary>
        /// <param name="connection">TCP连接</param>
        /// <param name="message">未识别的消息</param>
        protected override void OnUnhandledMessage(TcpConnection connection, IMessage message)
        {
            _unhandledMessageCount++;
            Logger.Warning($"Unhandled message #{_unhandledMessageCount} from {connection.Name}: {message.GetType().Name}");
            
            // 调用基类方法发送错误消息
            base.OnUnhandledMessage(connection, message);
        }

        /// <summary>
        /// 获取当前的统计信息
        /// </summary>
        /// <returns>统计信息字符串</returns>
        public string GetStatistics()
        {
            return $"CustomBusinessHandler Statistics:\n" +
                   $"  Echo Requests: {_echoRequestCount}\n" +
                   $"  Heartbeats: {_heartbeatCount}\n" +
                   $"  Status Messages: {_statusMessageCount}\n" +
                   $"  Unhandled Messages: {_unhandledMessageCount}\n" +
                   $"  Total Handlers: {GetRegisteredMessageTypes().Count}";
        }
    }
}